package com.zrq.secondkill.controller;

import com.zrq.secondkill.error.BusinessException;
import com.zrq.secondkill.response.CommonReturnType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    private static final int MAP_SIZE=2;

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonReturnType handle(Exception e){
        Map<String,Object> map=new HashMap<>(MAP_SIZE);
        if(e instanceof BusinessException){
            BusinessException businessException= (BusinessException) e;
            log.error("全局异常捕获器: "+businessException.getErrMsg(),e);
            map.put("errCode",businessException.getErrCode());
            map.put("errMsg",businessException.getErrMsg());
        }
        return CommonReturnType.create("fail",map);
    }
}
